package com.anran.controller;

import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author: anran
 * @Date: 2022-11-11
 */

@RestController
@CrossOrigin
public class PushController {

//    private static ConcurrentHashMap<String,SseEmitter> map = new ConcurrentHashMap<>();


    public static Map<String, SseEmitter> map = new HashMap<>();


    @GetMapping("/connect")
    public SseEmitter connect(@RequestParam String id){

        SseEmitter sseEmitter = new SseEmitter(0l);
        map.put(id, sseEmitter);
        System.out.println("建立成功: " + id);

        return sseEmitter;
    }

    @GetMapping("/push")
    public String push(@RequestParam String id , @RequestParam String content){
        try {
            if (map.containsKey(id)){
                SseEmitter sseEmitter = map.get(id);
                sseEmitter.send(content);
            }else {
                return "推送失败";
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println(e);
        }
        System.out.println("给用户："+id+",发送了消息："+content);
        return "给用户："+id+",发送了消息："+content;
    }




}
